import UiUtil from "../../../GameFramework/util/UiUtil";
import { EPockerStatus } from "../../ConfigEnum";
import UiPocker from "../../View/UiPocker/UiPocker";
import {GameDB, Pocker} from "../GameDB";

const {ccclass, property} = cc._decorator;

@ccclass
export default class GameView extends cc.Component {
	/*****************************************
  * property
  *****************************************/
	@property(cc.Prefab) uiPockerPrefab:cc.Prefab = null;
	@property(cc.Node) initPockersArea:cc.Node = null;
	@property(cc.Node) closeSendArea:cc.Node = null;
	@property(cc.Node) openSendArea:cc.Node = null;
	@property([cc.Node]) receiveAreaList:cc.Node[] = [];
	@property(cc.Node) playGroupRoot:cc.Node = null;

	private gameDB:GameDB = null;
	/*****************************************
	* lifecycle
	*****************************************/
	onLoad(){}

	/*****************************************
   * private API
   *****************************************/
	private createUiPocker(pocker:Pocker):UiPocker{
    let uiPockerNode = cc.instantiate(this.uiPockerPrefab);
    let uiPocker:UiPocker =uiPockerNode.getComponent('UiPocker');
    uiPocker.init(pocker);
    return uiPocker;
  }

	onPlay(){
		let stack:cc.Node[] = [];
		for (let i = this.initPockersArea.children.length-1; i >= 0; i--) {
			let child = this.initPockersArea.children[i];
			this.initPockersArea.removeChild(child);
			stack.push(child);
		}
		for (let i = stack.length-1; i >= 0; i--) {
			let child = stack[i];
			this.closeSendArea.addChild(child);
		}
	}

	/*****************************************
   * public API
   *****************************************/
	public initPockers(pockers:Pocker[]){
		pockers.forEach((pocker,i)=>{
			let uiPocker:UiPocker = this.createUiPocker(pocker);
			uiPocker.node.x=0.2*i;
			uiPocker.node.y=0.2*i;
			this.initPockersArea.addChild(uiPocker.node);
		})
	}

	public onEventInit(eventName:string, eventAttributes:any){
		let pockers = eventAttributes.pockers;
		this.initPockers(pockers);
	}

	public onEventPlay(){
		this.onPlay();
	}

	public onEventInitGroupCard(eventName:string, eventAttributes:any){
		let {groupIndex,cardIndex,pocker} = eventAttributes;
		let index = GameDB.CONST_PLAY_GROUPS*cardIndex - cardIndex*(cardIndex-1)/2 - cardIndex + groupIndex;
		let pockerViewNode = pocker.view.node;
		UiUtil.move(pockerViewNode,this.playGroupRoot);
		pockerViewNode.zIndex = index; 

		let delay = index*0.05;
		let px = groupIndex*90;
		if(pocker.ePockerStatus==EPockerStatus.CLOSE){
			cc.tween(pockerViewNode)
				.delay(delay)
				.to(0.5,{position:cc.v2(px,-30*cardIndex)})
				.start();
		}else{
			cc.tween(pockerViewNode)
				.delay(delay)
				.to(0.5,{position:cc.v2(px,-30*cardIndex)})
				.to(0.3,{scaleX:0})
				.call(()=>{
					pocker.view.refresh();
				})
				.to(0.3,{scaleX:1})
				.start();
		}
	}
}
